package com.media;

import java.time.Duration;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.media.input.TcpDecoderHandler;
import com.media.input.UdpDecoderHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import reactor.core.publisher.Flux;
import reactor.netty.tcp.TcpServer;
import reactor.netty.udp.UdpServer;

@SpringBootApplication
public class Run {

	public static void main(String[] args) {
		SpringApplication.run(Run.class, args);
	}
	
	@Bean
	CommandLineRunner serverRunner(UdpDecoderHandler udpDecoderHandler, TcpDecoderHandler tcpDecoderHandler) {
		return strings -> {
			createUdpServer(udpDecoderHandler);
			createTcpServer(tcpDecoderHandler);
		};
	}
	/**
	 * 创建UDP Server
	 * 
	 * @param udpDecoderHanlder： 解析UDP Client上报数据handler
	 */
	private void createUdpServer(UdpDecoderHandler udpDecoderHandler) {
		UdpServer.create().handle((in, out) -> {
			in.receive().asByteArray().subscribe();
			return Flux.never();
		})
		.doOnBound(conn -> conn.addHandlerLast("decoder", udpDecoderHandler)) // 可以添加多个handler
		.host("192.168.8.95")
		.port(8888)
		.bindNow(Duration.ofSeconds(30));
	}
	/***

	创建TCP Server*
	@param tcpDecoderHanlder： 解析TCP Client上报数据的handler*/

	private void createTcpServer(TcpDecoderHandler tcpDecoderHandler) {
		TcpServer.create().handle((in, out) -> {
			in.receive().asByteArray().subscribe();
			return Flux.never();
		})
		.doOnConnection(conn -> conn.addHandler(tcpDecoderHandler)) // 实例只写了如何添加handler,可添加delimiter，tcp生命周期，decoder，encoder等handler
		.host("192.168.8.95")
		.port(8888)
		.bindNow();
	}


}
